package com.hk.webapp.controller.admin;


import com.hk.webapp.annotations.SkipPermission;
import com.hk.webapp.bean.SysRole;
import com.hk.webapp.bean.SysUser;
import com.hk.webapp.bean.SysUserRole;
import com.hk.webapp.service.SysRoleService;
import com.hk.webapp.service.SysUserRoleService;
import com.hk.webapp.service.SysUserService;
import com.hk.webapp.utils.encryptions.AESUtils;
import com.hk.webapp.vo.*;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.hk.webapp.vo.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Arrays.asList;

@RestController
public class SysUserController extends AdminBaseController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysUserRoleService sysUserRoleService;

    @SkipPermission
    @PostMapping("/SysUser/Info")
    public ResultVo info(@RequestHeader(value = "userId", required = false) Integer userId){
        SysUser sysUser= sysUserService.getEntityById(userId);
        if (sysUser.getIsLock()==1){
            return  ResultVo.createByError("用户已被锁定");
        }
        //查询角色
        List<SysRole> roleList;
        if (sysUser.getIsSuper()==1){
            List<Integer> ids=new ArrayList<>();
            ids.add(1);
            roleList=sysRoleService.getEntityByIds(ids);
        }else{
            //获取角色
            List<SysUserRole> userRoleList=sysUserRoleService.getEntityListByUserId(userId);
            if (userRoleList.size()>0){
                roleList=sysRoleService.getEntityByIds(userRoleList.parallelStream().map(SysUserRole::getSysRoleId).collect(Collectors.toList()));
            }else{
                roleList=new ArrayList<>();
            }

        }
        HashMap<String, Object> map = Maps.newHashMap();
        map.put("avatar",sysUser.getAvatar());
        map.put("email",sysUser.getEmail());
        map.put("user_name",sysUser.getUserName());
        map.put("real_name",sysUser.getRealName());
        map.put("phone",sysUser.getPhone());
        map.put("remark",sysUser.getRemark());
        map.put("roles",roleList.parallelStream().map(c->{
            HashMap<String,Object> role=Maps.newHashMap();
            role.put("id",c.getId());
            role.put("name",c.getName());
            return role;
        }).collect(Collectors.toList()));
        map.put("email",sysUser.getEmail());
        map.put("last_login_ip",sysUser.getLastLoginIp());
        map.put("last_login_time",sysUser.getLastLoginTime());
        map.put("last_login_city",sysUser.getLastLoginCity());
        map.put("cur_login_ip",sysUser.getCurLoginIp());
        map.put("cur_login_time",sysUser.getCurLoginTime());
        map.put("cur_login_city",sysUser.getCurLoginCity());
        map.put("login_count",sysUser.getLoginCount());

        return  ResultVo.createBySuccessData(map);
    }

    @PostMapping("/SysUser/Edit")
    public ResultVo edit(@RequestHeader(value = "userId", required = false) Integer userId,@RequestBody @Valid SysUserVo vo){
        SysUser sysUser=new SysUser();
        sysUser.setRealName(vo.getReal_name());
        sysUser.setPhone(vo.getPhone());
        sysUser.setEmail(vo.getEmail());
        sysUser.setRemark(vo.getRemark());
        sysUser.setId(userId);
        if(sysUserService.updateSysUser(sysUser)>0){
            return ResultVo.createBySuccessData("succeed");
        }
        return  ResultVo.createByError("保存失败");
    }

    @SkipPermission
    @PostMapping("/SysUser/ResetPwd")
    public ResultVo resetPwd(@RequestHeader(value = "userId", required = false) Integer userId,@RequestBody @Valid ResetPwdVo vo) throws Exception{
        if (!vo.getNewPwd().equals(vo.getNewPwd2())){
            return ResultVo.createByError("两次密码不一致");
        }
        //1.0 验证旧密码
        SysUser sysUser= sysUserService.getEntityById(userId);
        if(sysUser==null){
            return ResultVo.createByError("修改失败");
        }
        if(!AESUtils.decrypt(sysUser.getPasswd(),sysUser.getSalt()).equals(vo.getOldPwd())){
            return ResultVo.createByError("旧密码验证失败");
        }
        //2.0 设置新密码
        sysUser.setPasswd(AESUtils.encrypt(vo.getNewPwd2(),sysUser.getSalt()));

        if(sysUserService.resetPasswd(sysUser)>0){
            return  ResultVo.createBySuccessData("succeed");
        }
        return ResultVo.createByError("修改失败");
    }

    @PostMapping("/SysUser/GetPageList")
    public ResultVo getPageList(@RequestBody PageVo vo){

        PageInfo<SysUser> plist=sysUserService.getPageList(vo);
        List<SysUser> list=plist.getList();



        //查询所有用户与角色关系
        List<Integer> sysUserIds=list.parallelStream().map(SysUser::getId).collect(Collectors.toList());
        List<SysUserRole> userRoleList=sysUserRoleService.getEntityListByUserIds(sysUserIds);
        //获取包含的角色
        List<Integer> sysRoleIds=userRoleList.parallelStream().map(SysUserRole::getSysRoleId).collect(Collectors.toList());
        List<SysRole> roleList = sysRoleService.getEntityByIds(sysRoleIds);
        //合并
        List<HashMap> mapList=new ArrayList<>();

        for (SysUser sysUser : list) {
            HashMap<String,Object> map=Maps.newHashMap();
            map.put("id",sysUser.getId());
            map.put("avatar",sysUser.getAvatar());
            map.put("create_time",sysUser.getCreateTime());
            map.put("email",sysUser.getEmail());
            map.put("is_lock",sysUser.getIsLock());
            map.put("is_super",sysUser.getIsSuper());
            map.put("phone",sysUser.getPhone());
            map.put("real_name",sysUser.getRealName());
            map.put("user_name",sysUser.getUserName());
            List<SysUserRole> sysUserRoleList= userRoleList.parallelStream().filter(c->c.getSysUserId()==sysUser.getId()).collect(Collectors.toList());
            List<String> roleNameList=new ArrayList<>();
            for (SysUserRole sysUserRole: sysUserRoleList) {
                roleNameList.addAll(roleList.parallelStream().filter(c->c.getId()==sysUserRole.getSysRoleId()).map(SysRole::getName).collect(Collectors.toList()));
            }
            map.put("roles",roleNameList);
            mapList.add(map);
        }
        return ResultVo.createBySuccessData(mapList,plist.getTotal());
    }


    @GetMapping("/SysUser/GetInfoById")
    public ResultVo getInfoById(int id){
        SysUser sysUser= sysUserService.getEntityById(id);
        if(sysUser==null){
            return ResultVo.createByError("数据不存在");
        }
        //获取角色数组
        List<SysUserRole> sysUserRolesList=sysUserRoleService.getEntityListByUserId(sysUser.getId());
        HashMap<String,Object> map=Maps.newHashMap();
        map.put("id",sysUser.getId());
        map.put("user_name",sysUser.getUserName());
        map.put("phone",sysUser.getPhone());
        map.put("email",sysUser.getEmail());
        map.put("real_name",sysUser.getRealName());
        map.put("passwd",sysUser.getPasswd());
        map.put("remark",sysUser.getRemark());
        map.put("roleIds",sysUserRolesList.parallelStream().map(SysUserRole::getSysRoleId).collect(Collectors.toList()));

        return ResultVo.createBySuccessData(map);
    }

    @PostMapping("/SysUser/EditSysUser")
    public ResultVo editSysUser(@RequestBody @Valid EditSysUserVo vo){
        //1.0 验证角色
        if (vo.getRoleIds().size()==0){
            return ResultVo.createByError("请选择角色");
        }
        //1.1 验证用户是否存在
        SysUser sysUser=sysUserService.getEntityById(vo.getId());
        if (sysUser==null){
            return ResultVo.createByError("数据不存在");
        }
        //2.0 获取角色
        List<SysRole> roleList = sysRoleService.getEntityByIds(vo.getRoleIds());
        if (roleList.size()==0){
            return ResultVo.createByError("角色不存在");
        }
        //3.0 修改管理员
        sysUser.setRealName(vo.getReal_name());
        sysUser.setEmail(vo.getEmail());
        sysUser.setPhone(vo.getPhone());
        sysUser.setRemark(vo.getRemark());
        if(sysUserService.updateSysUser(sysUser)==0){
            return ResultVo.createByError("修改失败");
        }
        //4.0 删除用户角色关系
        int row= sysUserRoleService.deleteByUserIds(asList(sysUser.getId()));
        //5.0 创建用户角色关系
        for (Integer item : vo.getRoleIds()) {
            SysUserRole sysUserRole=new SysUserRole();
            sysUserRole.setCreateTime(new Date());
            sysUserRole.setSysUserId(sysUser.getId());
            sysUserRole.setSysRoleId(item);
            sysUserRole.setIsDeleted(0);
            sysUserRoleService.insert(sysUserRole);
        }
        return ResultVo.createBySuccessData("succeed");
    }

    @PostMapping("/SysUser/ChangeLock")
    public ResultVo changeLock(@RequestBody @Valid ChangeLockVo vo){
        if (vo.getIs_lock()!=0&&vo.getIs_lock()!=1){
            return ResultVo.createByError("非法参数");
        }
        if (vo.getId()==1){
            return ResultVo.createByError("无法操作超级管理员");
        }
        SysUser sysUser=sysUserService.getEntityById(vo.getId());
        if(sysUser==null){
            return ResultVo.createByError("管理员不存在");
        }
        if(sysUser.getIsLock()==vo.getIs_lock()){
            return ResultVo.createBySuccessData("succeed");
        }
        sysUser.setIsLock(vo.getIs_lock());
        if(sysUserService.changeLock(sysUser)>0){
            return ResultVo.createBySuccessData("succeed");
        }
        return ResultVo.createByError("非法请求");
    }

    @PostMapping("/SysUser/AddSysUser")
    public ResultVo addSysUser(@RequestBody @Valid EditSysUserVo vo) throws Exception{
        //1.0 验证角色
        if (vo.getRoleIds().size()==0){
            return ResultVo.createByError("请选择角色");
        }
        //2.0 获取角色
        List<SysRole> roleList = sysRoleService.getEntityByIds(vo.getRoleIds());
        if(roleList.size()==0){
            return ResultVo.createByError("角色不存在");
        }
        //3.0 添加管理员
        String salt=UUID.randomUUID().toString().replace("-", "");
        String passwd = AESUtils.encrypt(vo.getPasswd(),salt);
        SysUser sysUser=new SysUser();
        sysUser.setUserName(vo.getUser_name());
        sysUser.setRealName(vo.getReal_name());
        sysUser.setPhone(vo.getPhone());
        sysUser.setEmail(vo.getEmail());
        sysUser.setCreateTime(new Date());
        sysUser.setSalt(salt);
        sysUser.setPasswd(passwd);

        Integer uid= sysUserService.insert(sysUser);
        if (uid==0){
            return ResultVo.createByError("添加失败");
        }
        //4.0 创建用户角色关系
        for (Integer roleId : vo.getRoleIds()) {
            SysUserRole sysUserRole=new SysUserRole();
            sysUserRole.setSysRoleId(roleId);
            sysUserRole.setSysUserId(sysUser.getId());
            sysUserRole.setCreateTime(new Date());
            sysUserRole.setIsDeleted(0);

            sysUserRoleService.insert(sysUserRole);
        }
        return ResultVo.createBySuccessData("succeed");
    }

    @PostMapping("/SysUser/DelSysUser")
    public ResultVo delSysUser(@RequestBody IdsVo vo){
        if (vo.getIds().contains(1)){
            return ResultVo.createByError("无法删除超级管理员");
        }
        if(sysUserService.deleteByIds(vo.getIds())>0){
            //删除管理员角色关系
            sysUserRoleService.deleteByUserIds(vo.getIds());

            return ResultVo.createBySuccessData("succeed");
        }
        return ResultVo.createByError("非法请求");
    }

    @PostMapping("/SysUser/ResetPwds")
    public ResultVo resetPwds(@RequestBody ResetPwdsVo vo)throws Exception {
        if (vo.getIds().size()==0){
            return ResultVo.createByError("参数不完整");
        }
        if (vo.getPwd().length()<5){
            return ResultVo.createByError("密码长度过短");
        }
        //获取所有管理员
        List<SysUser> list = sysUserService.getEntityByIds(vo.getIds());
        if (list.size()!=vo.getIds().size())
        {
            return ResultVo.createByError("未查询到相关管理员信息");
        }
        //批量修改密码
        for (SysUser sysUser: list) {
            sysUser.setPasswd(AESUtils.encrypt(vo.getPwd(),sysUser.getSalt()));
            sysUserService.resetPasswd(sysUser);
        }
        return ResultVo.createBySuccessData("succeed");
    }


}
